/**
 * 
 */
package cn.ad.server.web.spring.service.actions;

import cn.ad.server.web.log.IAdServerLogger;
import cn.ad.server.web.spring.model.BidAdRequest;
import cn.ad.server.web.spring.model.BidAdResponse;
import cn.ad.server.web.spring.model.adview.*;
import cn.ad.server.web.spring.service.actions.context.AdContextBuilder;
import cn.ad.server.web.spring.service.actions.context.BidContext;
import cn.ad.server.web.spring.service.biz.AdViewImpressionMatchService;
import cn.ad.server.biz.internal.AdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 *
 */
@Component("action-bid-adview")
public class AdViewBIDAction extends BidAdRequestAction {

	private static Logger logger = LoggerFactory.getLogger(AdViewBIDAction.class);

	@Autowired
	private AdViewImpressionMatchService adViewImpressionHandler;

	@Autowired
	private IAdServerLogger loggerService;

	@Autowired
	private AdService adService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * cn.ad.server.web.spring.service.actions.BidAdService#
	 * doRequest(cn.falconnect.adserver.adapter.BidAdRequest)
	 */
	@Override
	BidAdResponse doRequest(BidAdRequest request) {
		try {
			AdViewBidRequest adViewBidRequest = (AdViewBidRequest) request;
			BidContext context = AdContextBuilder.build(adViewBidRequest);
			return doProcess(adViewBidRequest, context);
		} finally {
			this.adService.unbond();
		}
	}

	public BidAdResponse doProcess(AdViewBidRequest adViewBidRequest, BidContext bidContext) {
		AdViewBidResponse adViewBidResponse = new AdViewBidResponse();
		// 处理参数解析异常的处理
		if (bidContext == null) {
			if (adViewBidRequest != null) {
				adViewBidResponse.setBidid(adViewBidRequest.getId());
			}
			// adViewBidResponse.setNbr(AdViewBidResponse.NOT_BID_REASON.INVALID_REQUEST.getValue());
			return null;
		}

		adViewBidResponse.setId(adViewBidRequest.getId());

		// 竞价方式
		AdViewBidRequest.AT at = adViewBidRequest.getAt();

		AdViewImpression[] impressions = adViewBidRequest.getImp();

		SeatBid seatBid = new SeatBid();
		adViewBidResponse.setSeatbid(new SeatBid[] { seatBid });
		Bid[] bids = new Bid[impressions.length];
		seatBid.setBid(bids);
		for (int i = 0; i < impressions.length; i++) {

			BidContext impBidContext = (BidContext) bidContext.clone();
			Bid bid = new Bid();
			bid.setImpid(impressions[i].getId());
			try {
				bids[i] = adViewImpressionHandler.handler(impressions[i], impBidContext);
			} catch (Exception e) {
				logger.error("Threre a exception on Adview Impression handler. error: {}", e.getMessage(), e);
			} finally {
				// 记录日志
				loggerService.logAdBidRequest(impBidContext);
			}

		}

		boolean hasBid = false;
		for (Bid bid : bids) {
			if (bid != null) {
				hasBid = true;
				break;
			}
		}

		if (!hasBid) {
			adViewBidResponse = null;
		}

		return adViewBidResponse;

	}
}
